package com.lx.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lx.dao.OrderDao;
import com.lx.entity.Order;
import com.lx.entity.OrderDetail;
import com.lx.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 2025/9/17 9:55
 * author: 向远洋
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public PageInfo<Order> getPageInfo(Map<String, Object> params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()), Integer.parseInt(params.get("pageSize").toString()));
        List<Order> orders = orderDao.selectAllOrder(params);
        //获取订单id集合，再查询订单集合相关的订单详情集合
        List<Integer> ids = orders.stream().map(Order::getId).collect(Collectors.toList());
        List<OrderDetail> orderDetails = orderDao.selectOrderDetailList(ids);
        //建立订单与详情的映射关系：
        Map<Integer, List<OrderDetail>> detailsMap = orderDetails.stream()
                .collect(Collectors.groupingBy(OrderDetail::getOrderId));
        //设置订单详情到对应订单：
        orders.forEach(order -> order.setOrderDetailList(detailsMap.get(order.getId())));
        return new PageInfo<>(orders);
    }

    @Override
    public List<Order> getOrderCarRecent(Integer id) throws JsonProcessingException {
        //先判断redis中有没有购物车订单，有直接获取，后续修改都修改redis中的数据
        String order = stringRedisTemplate.opsForValue().get(id.toString() + "orderCar");
        ObjectMapper mapper = new ObjectMapper();
        if(order == null) {
            List<Order> orders = orderDao.selectOrderCarRecent(id);
            //如果用户目前还没有购物车订单，新增一个空购物车订单
            if(orders.isEmpty()) {
                if(orderDao.insertOrder(id) == 1) System.out.println("新增用户：" +id +" 的空购物车订单成功");
                orders = orderDao.selectOrderCarRecent(id);
            }
            String orderJson = null;
            try {
                orderJson = mapper.writeValueAsString(orders);
                stringRedisTemplate.opsForValue().set(id.toString() + "orderCar", orderJson);
                return orders;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        //order != null
        CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, Order.class);
        String orderJson = stringRedisTemplate.opsForValue().get(id.toString() + "orderCar");
        return mapper.readValue(orderJson, javaType);
    }

    @Override
    public Order getEasyOrderById(Integer id) {
        return orderDao.selectEasyOrderById(id);
    }

    @Override
    public void modifyRedisOrderCar(Order car) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String orderJson = mapper.writeValueAsString(car);
            stringRedisTemplate.opsForValue().set(car.getId().toString() + "orderCar", orderJson);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean modifyDBOrderCar(Order car) {
        return orderDao.updateOrderById(car) == 1;
    }

    @Override
    public boolean modifyOrderStatusBySerialNumber(String serialNumber, Integer isPay) {
        return orderDao.updateOrderStatusBySerialNumber(serialNumber, isPay) == 1;
    }

    @Override
    public boolean modifyOrderStatusById(Integer id, Integer isPay) {
        return orderDao.updateOrderStatusById(id, isPay) == 1;
    }

    @Override
    public boolean addOrderDetail(OrderDetail orderDetail) {
        return orderDao.insertOneOrderDetail(orderDetail) == 1;
    }

    @Override
    public boolean addOrderDetailList(Order order) {
        int len = order.getOrderDetailList().size();
        return len == orderDao.insertOrderDetails(order.getOrderDetailList(), order.getId());
    }

    @Override
    public List<OrderDetail> getOrderDetailList(List<Integer> ids) {
        return orderDao.selectOrderDetailList(ids);
    }

    @Override
    public boolean deleteOrder(int id) {
        orderDao.deleteOrderDetailByOrderId(id);
        return orderDao.deleteOrderById(id) == 1;
    }

}
